package com.test.BTClient.Utils;

import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;

/**
 * Created by wuguitong on 2017/5/17.
 */
public class Utils {
    /**
     * 字符串转换成十六进制字符串
     * @param String str 待转换的ASCII字符串
     * @return String 每个Byte之间空格分隔，如: [61 6C 6B]
     */
    public static String str2HexStr(String str)
    {

        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;

        for (int i = 0; i < bs.length; i++)
        {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
            sb.append(' ');
        }
        return sb.toString().trim();
    }

    /**
     * 十六进制转换字符串
     * @param String str Byte字符串(Byte之间无分隔符 如:[616C6B])
     * @return String 对应的字符串
     */
    public static String hexStr2Str(String hexStr)
    {
        String str = "0123456789ABCDEF";
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int n;

        for (int i = 0; i < bytes.length; i++)
        {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        return new String(bytes);
    }

    /**
     * bytes转换成十六进制字符串
     * @param byte[] b byte数组
     * @return String 每个Byte值之间空格分隔
     */
    public static String byte2HexStr(byte[] b)
    {
        String stmp="";
        StringBuilder sb = new StringBuilder("");
        for (int n=0;n<b.length;n++)
        {
            stmp = Integer.toHexString(b[n] & 0xFF);
            sb.append((stmp.length()==1)? "0"+stmp : stmp);
            sb.append(" ");
        }
        return sb.toString().toUpperCase().trim();
    }

    /**
     * bytes字符串转换为Byte值
     * @param String src Byte字符串，每个Byte之间没有分隔符
     * @return byte[]
     */
    public static byte[] hexStr2Bytes(String src)
    {
        int m=0,n=0,tmp;
        int l=src.length()/2;
        System.out.println(l);
        byte[] ret = new byte[l];
        for (int i = 0; i < l; i++)
        {
            m=i*2+1;
            n=m+1;
            tmp = Integer.decode("0x" + src.substring(i * 2, m) + src.substring(m, n));
            ret[i] = (byte)tmp;
        }
        return ret;
    }

    /**
     * String的字符串转换成unicode的String
     * @param String strText 全角字符串
     * @return String 每个unicode之间无分隔符
     * @throws Exception
     */
    public static String strToUnicode(String strText)
            throws Exception
    {
        char c;
        StringBuilder str = new StringBuilder();
        int intAsc;
        String strHex;
        for (int i = 0; i < strText.length(); i++)
        {
            c = strText.charAt(i);
            intAsc = (int) c;
            strHex = Integer.toHexString(intAsc);
            if (intAsc > 128)
                str.append("\\u" + strHex);
            else // 低位在前面补00
                str.append("\\u00" + strHex);
        }
        return str.toString();
    }

    /**
     * unicode的String转换成String的字符串
     * @param String hex 16进制值字符串 （一个unicode为2byte）
     * @return String 全角字符串
     */
    public static String unicodeToString(String hex)
    {
        int t = hex.length() / 6;
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < t; i++)
        {
            String s = hex.substring(i * 6, (i + 1) * 6);
            // 高位需要补上00再转
            String s1 = s.substring(2, 4) + "00";
            // 低位直接转
            String s2 = s.substring(4);
            // 将16进制的string转为int
            int n = Integer.valueOf(s1, 16) + Integer.valueOf(s2, 16);
            // 将int转换为字符
            char[] chars = Character.toChars(n);
            str.append(new String(chars));
        }
        return str.toString();
    }
    public static class CustomTextWatcher implements TextWatcher {

        private static final String TAG = "CustomTextWatcher";

        private boolean mFormat;

        private boolean mInvalid;

        private int mSelection;

        private String mLastText;

        private EditText mEditText;

        public CustomTextWatcher(EditText editText) {

            super();
            mFormat = false;
            mInvalid = false;
            mLastText = "";
            this.mEditText = editText;
            this.mEditText.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
        }

        @Override
        public void beforeTextChanged(CharSequence charSequence, int start,
                                      int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int start, int before,
                                  int count) {

            try {

                String temp = charSequence.toString();

                // Set selection.
                if (mLastText.equals(temp)) {
                    if (mInvalid) {
                        mSelection -= 1;
                    } else {
                        if ((mSelection >= 1) && (temp.length() > mSelection - 1)
                                && (temp.charAt(mSelection - 1)) == ' ') {
                            mSelection += 1;
                        }
                    }
                    int length = mLastText.length();
                    if (mSelection > length) {

                        mEditText.setSelection(length);
                    } else {

                        mEditText.setSelection(mSelection);
                    }
                    mFormat = false;
                    mInvalid = false;
                    return;
                }

                mFormat = true;
                mSelection = start;

                // Delete operation.
                if (count == 0) {
                    if ((mSelection >= 1) && (temp.length() > mSelection - 1)
                            && (temp.charAt(mSelection - 1)) == ' ') {
                        mSelection -= 1;
                    }

                    return;
                }

                // Input operation.
                mSelection += count;
                char[] lastChar = (temp.substring(start, start + count))
                        .toCharArray();
                int mid = lastChar[0];
                if (mid >= 48 && mid <= 57) {
                /* 1-9. */
                } else if (mid >= 65 && mid <= 70) {
                /* A-F. */
                } else if (mid >= 97 && mid <= 102) {
                /* a-f. */
                } else {
                /* Invalid input. */
                    mInvalid = true;
                    temp = temp.substring(0, start)
                            + temp.substring(start + count, temp.length());
                    mEditText.setText(temp);
                    return;
                }

            } catch (Exception e) {
                Log.i(TAG, e.toString());
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {

            try {

            /* Format input. */
                if (mFormat) {
                    StringBuilder text = new StringBuilder();
                    text.append(editable.toString().replace(" ", ""));
                    int length = text.length();
                    int sum = (length % 2 == 0) ? (length / 2) - 1 : (length / 2);
                    for (int offset = 2, index = 0; index < sum; offset += 3, index++) {

                        text.insert(offset, " ");
                    }
                    mLastText = text.toString();
                    mEditText.setText(text);
                }
            } catch (Exception e) {
                Log.i(TAG, e.toString());
            }
        }

    }

}
